import React, { Fragment } from 'react';
import { connect } from 'umi';
import { Row, Col, Tabs, Icon, Empty } from 'antd';
import { get as getPath } from 'object-path';
import ReactEcharts from 'echarts-for-react';
import { formatMessage } from 'umi';
import moment from 'moment';
import LinkTo from '@/components/LinkTo';
import increment from '@/assets/invoice_maker.jpg';
import incrementText from '@/assets/invoice_maker_text.png';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import AuthComponent from '@/utils/auth/AuthComponent';
import AuthCode from '@/utils/auth/AuthCode';
import authHelper from '@/utils/auth/helper';
import { withRoutePage } from '@/utils/enhanceUtils';
import style from './Gateway.less';
// 组件
// import Authorized from '@/utils/Authorized';
import NoticeList from './gatewayCompanent/NoticeList';
import WorkList from './gatewayCompanent/WorkList';
import ThreeList from './gatewayCompanent/ThreeList';
import DateList from './gatewayCompanent/DateList';


// const { authCode } = new AuthCode('portal:main');
const { checkCode } = authHelper;

class Gateway extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            wnvalue: null,
            goMore: 1,
            sixMonth: []
        };
        this.authCode = new AuthCode(props.route.code).authCode;
    }

    componentWillMount() {
        this.fetchWork();
        const { dispatch } = this.props;
        dispatch({
            type: 'gateway/saveCharts',
            payload: {
                pieData: [],
                axisData: []
            }
        });
        dispatch({
            type: 'gateway/getNewOption',
            payload: {
                option3data: [],
                colorChoose: '#3BA0FF'
            }
        });
    }

    componentDidMount() {
        // 获取前6个月作为数组,作为柱状图x轴渲染的title
        const thesixMonth = ['1月', '2月', '3月', '4月', '5月', '6月'];
        thesixMonth.forEach((element, index) => {
            thesixMonth[index] = `${moment()
                .subtract(index, 'months')
                .format('M')}月`;
        });
        this.setState({
            sixMonth: thesixMonth.reverse()
        });
        this.fetchList();
        this.getCharts(this.props);
    }

    componentWillReceiveProps(nextProps) {
        const { filterRoutes: nextFilterRoutes } = nextProps.menu;
        const {
            menu: { filterRoutes }
        } = this.props;

        if (JSON.stringify(nextFilterRoutes) !== JSON.stringify(filterRoutes)) {
            this.getCharts(nextProps);
        }
    }

    // 获取通知公告/规章制度 数据
    fetchList = () => {
        const { dispatch } = this.props;
        dispatch({
            type: 'gateway/fetchList'
        });
    };

    // 获取待我审批等数据
    fetchWork = () => {
        const { dispatch } = this.props;
        dispatch({
            type: 'gateway/getWorkData',
            payload: {
                pageNo: 1,
                pageSize: 4
            }
        });
    };

    // 判断权限，获取图表数据
    getCharts = props => {
        const {
            dispatch,
            menu: { filterRoutes }
        } = props;
        // 获取公司/部門id
        const user = localStorage.getItem('user');
        const userInfo = user ? JSON.parse(user) : {};
        const paramsId = userInfo.companyId
            ? userInfo.companyId
            : userInfo.departmentId;
        const paramsFlag = userInfo.companyId ? 1 : 0;
        // const showMOdule = [];
        // 处理menu的权限标识符
        // const getRouterAuthority = (result, pathname) => {
        //     if (result && result.length > 0) {
        //         result.map(item => {
        //             showMOdule.push(item.url);
        //             if (
        //                 item.children !== undefined &&
        //                 item.children !== null &&
        //                 item.children.length > 0
        //             ) {
        //                 getRouterAuthority(item.children, pathname);
        //             }
        //             return showMOdule;
        //         });
        //     }
        //     let showorno = false;
        //     showMOdule.forEach(item => {
        //         if (item === pathname) {
        //             showorno = true;
        //         }
        //     });
        //     if (showorno) {
        //         return true;
        //     }
        //     return false;
        // };
        if (filterRoutes) {
            // 如果有人事报表模块的权限
            if (checkCode(this.authCode('hr'))) {
                // 如果有近六个月员工数量趋势的权限
                if (checkCode(this.authCode('hr:staffnum'))) {
                    // 获取柱状图数据
                    dispatch({
                        type: 'gateway/fetchAxis',
                        payload: {
                            id: paramsId,
                            orgFlag: paramsFlag
                        }
                    });
                }
                // 如果有组织分布的权限
                if (checkCode(this.authCode('hr:distribution'))) {
                    // 获取饼图数据
                    dispatch({
                        type: 'gateway/fetchPie',
                        payload: {
                            id: paramsId,
                            orgFlag: paramsFlag
                        }
                    });
                    // 设置内圈初始颜色
                    dispatch({
                        type: 'gateway/getNewOption',
                        payload: {
                            colorChoose: '#3BA0FF'
                        }
                    });
                }
            }
        }
    };

    // 环形饼状图外圈被点击
    onChartClick = param => {
        if (param.componentIndex === 1) {
            // console.log('环形饼状图外圈被点击---', param.name);
            const { dispatch, gateway } = this.props;
            const pieData = getPath(gateway, 'pieData', []);
            const params = getPath(pieData, `${param.dataIndex}.children`, []);
            dispatch({
                type: 'gateway/getNewOption',
                payload: {
                    option3data: params,
                    colorChoose: param.color,
                    chooseIndex: param.name
                }
            });
        }
    };

    /**
     *饼图legend 点击事件-确保内环跟随改变
     * bababbabl
     * @memberof Gateway
     */
    onLegendClick = param => {
        const { dispatch, gateway } = this.props;
        const pieData = getPath(gateway, 'pieData', []);
        const { pieColor } = gateway;
        let flage = false;
        // eslint-disable-next-line no-restricted-syntax
        for (const key in param.selected) {
            // eslint-disable-next-line no-prototype-builtins
            if (param.selected.hasOwnProperty(key)) {
                if (param.selected[key]) {
                    flage = true;
                    pieData.forEach((item, index) => {
                        if (item.name === key) {
                            // console.info(
                            //     '饼图legend 点击，当前应该选中---',
                            //     key
                            // );
                            const params = getPath(
                                pieData,
                                `${index}.children`,
                                []
                            );
                            const paramsColor = getPath(pieColor[index]);
                            /**
                             * TODO: 图例置灰后，点击会有其他色块乱跳，有大佬看到可以挑战一下自己
                             */
                            dispatch({
                                type: 'gateway/getNewOption',
                                payload: {
                                    option3data: params,
                                    colorChoose: paramsColor,
                                    chooseIndex: key
                                }
                            });
                            return true;
                        }
                        return true;
                    });
                    return false;
                }
            }
        }
        if (!flage) {
            dispatch({
                type: 'gateway/getNewOption',
                payload: {
                    option3data: []
                }
            });
        }
        return true;
    };

    render() {
        const { TabPane } = Tabs;
        const { gateway, route } = this.props;
        const { data, axisData, option3data, colorChoose, pieColor } = gateway;
        // const { filterRoutes } = authHelper;

        const pieData = getPath(gateway, 'pieData', []);
        if (data && data.noticeList) {
            data.noticeList = data.noticeList.filter(
                (item, index) => index < 3
            );
        }
        if (data && data.ruleList) {
            data.ruleList = data.ruleList.filter((item, index) => index < 3);
        }
        // const showMOdule = [];
        // 处理menu的权限标识符
        // const getRouterAuthority = (result, pathname) => {
        //     if (result && result.length > 0) {
        //         result.map(item => {
        //             showMOdule.push(item.url);
        //             if (
        //                 item.children !== undefined &&
        //                 item.children !== null &&
        //                 item.children.length > 0
        //             ) {
        //                 getRouterAuthority(item.children, pathname);
        //             }
        //             return showMOdule;
        //         });
        //     }
        //     let showorno = false;
        //     showMOdule.forEach(item => {
        //         if (item === pathname) {
        //             showorno = true;
        //         }
        //     });
        //     if (showorno) {
        //         return true;
        //     }
        //     return false;
        // };
        // 绘制柱状图
        const getOptionAxis = list => ({
            tooltip: {
                trigger: 'axis',
                backgroundColor: 'rgba(51,51,51,0.9)',
                padding: [10, 16],
                textStyle: {
                    fontSize: 11,
                    fontFamily: 'SFUIText-Regular',
                    fontWeight: '400',
                    color: 'rgba(255,255,255,1)',
                    lineHeight: '20px'
                }
            },
            legend: {
                icon: 'circle',
                itemWidth: 10,
                itemHeight: 10,
                itemGap: 20,
                x: 'center',
                selectedMode: false
            },
            xAxis: [
                {
                    type: 'category',
                    data: getPath(this.state, 'sixMonth'),
                    axisPointer: {
                        type: 'shadow'
                    },
                    axisLine: {
                        lineStyle: {
                            color: 'rgba(0,0,0,0.45)'
                        }
                    }
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    name: '总员工',
                    minInterval: 20,
                    splitLine: {
                        lineStyle: {
                            type: 'dashed'
                        }
                    },
                    axisLine: {
                        lineStyle: {
                            color: 'rgba(0,0,0,0.45)'
                        }
                    }
                },
                {
                    type: 'value',
                    name: '数量',
                    splitLine: {
                        lineStyle: {
                            type: 'dashed'
                        }
                    },
                    minInterval: 10,
                    axisLine: {
                        lineStyle: {
                            color: 'rgba(0,0,0,0.45)'
                        }
                    }
                }
            ],
            series:
                    list && list.length > 0
                        ? list.map(item => ({
                            name: item.name,
                            type: item.name === '总员工数' ? 'line' : 'bar',
                            data: item.value.map(subItem => subItem || 0),
                            itemStyle: {
                                normal: {
                                    color(param) {
                                        return pieColor[param.seriesIndex];
                                    },
                                    lineStyle: {
                                        color: '#3BA0FF'
                                    }
                                }
                            },
                            minInterval: 1,
                            yAxisIndex: item.name === '总员工数' ? 0 : 1
                        }))
                        : []
        });
        // 绘制饼图
        const getOptionPie = newPieData => {
            const requestData = Array.isArray(newPieData)
                ? newPieData.map(item => ({
                    name: item.name,
                    value: item.value,
                    selected:
                              item.name === getPath(gateway, 'chooseIndex')
                }))
                : [];
            const mydata = option3data.map((item, index) => ({
                name: item.name,
                value: item.value,
                itemStyle: {
                    normal: {
                        label: {
                            show: false
                        },
                        labelLine: {
                            show: false
                        },
                        color: colorChoose,
                        opacity: 1 - 0.1 * index
                    }
                }
            }));
            return {
                tooltip: {
                    trigger: 'item',
                    formatter(param) {
                        return `${param.marker} ${param.name}：${param.value}`;
                    }
                },
                legend: {
                    type: 'scroll',
                    data: requestData,
                    icon: 'circle',
                    itemWidth: 10,
                    itemHeight: 10,
                    itemGap: 20,
                    x: 'center',
                    selectedMode: false
                },
                series: [
                    {
                        name: '部门',
                        type: 'pie',
                        radius: [0, '35%'],
                        itemStyle: {
                            normal: {
                                label: {
                                    show: false
                                },
                                labelLine: {
                                    show: false
                                }
                            }
                        },
                        label: {
                            normal: {
                                position: 'inner'
                            }
                        },
                        labelLine: {
                            normal: {
                                show: false
                            }
                        },
                        data: mydata
                    },
                    {
                        name: '公司',
                        type: 'pie',
                        radius: ['49%', '65%'],
                        selectedMode: 'single',
                        itemStyle: {
                            normal: {
                                color(params) {
                                    return pieColor[params.dataIndex];
                                }
                            }
                        },
                        label: {
                            normal: {
                                position: 'inner',
                                formatter: '{d}%',
                                fontSize: 12
                            }
                        },
                        data: requestData
                    }
                ]
            };
        };
        const optionAxisEchart = (
            <ReactEcharts
                option={getOptionAxis(
                    axisData.list
                )}
                style={{
                    width: '100%',
                    height: '400px'
                }}
            />
        );
        const emptyBlock = (<Empty
            className={
                style.myEmpty
            }
            image={
                Empty.PRESENTED_IMAGE_SIMPLE
            }
        />)
        return (
            <Fragment>
                <PageHeaderWrapper>
                    <div className={style.wncontainer}>
                        <Row gutter={20} type="flex">
                            <Col
                                // className="gutter-row"
                                className={style.banner}
                                xs={{ span: 24 }}
                                xl={{ span: 13 }}
                                style={{
                                    height: '260px',
                                    paddingRight: '12px'
                                }}
                            >
                                <div
                                    style={{
                                        height: '100%',
                                        width: '100%',
                                        objectPosition: '50% 50%',
                                        borderRadius: '5px',
                                        overflow: 'hidden',
                                        position: 'relative'
                                    }}
                                >
                                    <img
                                        src={increment}
                                        alt={formatMessage({
                                            id: 'list.img.alt'
                                        })}
                                        className={style.wnImg}
                                    />
                                    <img
                                        src={incrementText}
                                        alt={formatMessage({
                                            id: 'list.img.alt'
                                        })}
                                        className={style.wnTextImg}
                                    />
                                </div>
                            </Col>
                            <Col
                                className="gutter-row"
                                xs={{ span: 24 }}
                                xl={{ span: 11 }}
                                style={{
                                    paddingLeft: '12px'
                                }}
                            >
                                <NoticeList data={data} route={route} />
                            </Col>
                        </Row>
                        <Row gutter={20} type="flex">
                            <Col
                                className="gutter-row"
                                xs={{ span: 24 }}
                                xl={{ span: 13 }}
                                style={{
                                    paddingRight: '12px'
                                }}
                            >
                                <WorkList route={route} />
                            </Col>
                            <Col
                                className="gutter-row"
                                xs={{ span: 24 }}
                                xl={{ span: 11 }}
                                style={{
                                    paddingLeft: '12px'
                                }}
                            >
                                <DateList />
                            </Col>
                        </Row>
                        <AuthComponent code={this.authCode('hr')}>
                            <Row gutter={20} type="flex">
                                <Col className="gutter-row" xs={{ span: 24 }}>
                                    <div className={style.bgfff}>
                                        <Tabs
                                            defaultActiveKey="chart1"
                                            className={style.wnTabs}
                                        >
                                            <TabPane
                                                tab={formatMessage({
                                                    id: 'list.charts.hr'
                                                })}
                                                key="chart1"
                                            >
                                                <Row
                                                    style={{
                                                        marginTop: '20px'
                                                    }}
                                                >
                                                    <AuthComponent
                                                        code={this.authCode(
                                                            'hr:staffnum'
                                                        )}
                                                    >
                                                        <Col
                                                            xs={{ span: 24 }}
                                                            xl={{ span: 12 }}
                                                            style={{
                                                                borderRight:
                                                                    '1px solid #eee'
                                                            }}
                                                        >
                                                            <p
                                                                className={
                                                                    style.wnchartsTitle
                                                                }
                                                            >
                                                                {formatMessage({
                                                                    id:
                                                                        'list.charts.hr.first'
                                                                })}
                                                            </p>
                                                            {axisData &&
                                                            axisData.list ? optionAxisEchart : emptyBlock}
                                                        </Col>
                                                    </AuthComponent>
                                                    <AuthComponent
                                                        code={this.authCode(
                                                            'hr:distribution'
                                                        )}
                                                    >
                                                        <Col
                                                            xs={{ span: 24 }}
                                                            xl={{ span: 12 }}
                                                            style={{
                                                                paddingLeft:
                                                                    '30px'
                                                            }}
                                                        >
                                                            <p
                                                                className={
                                                                    style.wnchartsTitle
                                                                }
                                                            >
                                                                {formatMessage({
                                                                    id:
                                                                        'list.charts.hr.second'
                                                                })}
                                                            </p>
                                                            <LinkTo
                                                                className={
                                                                    style.wnchart_more
                                                                }
                                                                to="/stat/orgs"
                                                            >
                                                                {formatMessage({
                                                                    id:
                                                                        'list.btn.more'
                                                                })}{' '}
                                                                <Icon type="right" />
                                                            </LinkTo>
                                                            {/* <a
                                                                className={
                                                                    style.wnchart_more
                                                                }
                                                                onClick={() => (
                                                                    history.push(
                                                                        '/stat/orgs'
                                                                    )
                                                                )}
                                                            >
                                                                {formatMessage({
                                                                    id:
                                                                        'list.btn.more'
                                                                })}{' '}
                                                                <Icon type="right" />
                                                            </a> */}
                                                            <div
                                                                style={{
                                                                    display:
                                                                        'flex',
                                                                    height:
                                                                        '400px',
                                                                    justifyContent:
                                                                        'space-sround'
                                                                }}
                                                                id="top"
                                                            >
                                                                {pieData &&
                                                                pieData.length >
                                                                    0 ? (
                                                                        <ReactEcharts
                                                                            option={getOptionPie(
                                                                                pieData
                                                                            )}
                                                                            onEvents={{
                                                                                click: this
                                                                                    .onChartClick,
                                                                                legendselectchanged: this
                                                                                    .onLegendClick
                                                                            }}
                                                                            style={{
                                                                                width:
                                                                                '100%',
                                                                                height:
                                                                                '400px'
                                                                            }}
                                                                        />
                                                                    ) : (
                                                                        <Empty
                                                                            className={
                                                                                style.myEmpty
                                                                            }
                                                                            image={
                                                                                Empty.PRESENTED_IMAGE_SIMPLE
                                                                            }
                                                                        />
                                                                    )}
                                                            </div>
                                                        </Col>
                                                    </AuthComponent>
                                                </Row>
                                            </TabPane>
                                            {/* <TabPane
                                            tab={formatMessage({
                                                id: 'list.charts.xz'
                                            })}
                                            key="chart2"
                                        />
                                        <TabPane
                                            tab={formatMessage({
                                                id: 'list.charts.cw'
                                            })}
                                            key="chart3"
                                        />
                                        <TabPane
                                            tab={formatMessage({
                                                id: 'list.charts.xm'
                                            })}
                                            key="chart4"
                                        /> */}
                                        </Tabs>
                                    </div>
                                </Col>
                            </Row>
                        </AuthComponent>
                        <Row gutter={20} type="flex">
                            <Col className="gutter-row" xs={{ span: 24 }}>
                                <ThreeList />
                            </Col>
                        </Row>
                    </div>
                </PageHeaderWrapper>
            </Fragment>
        );
    }
}
export default withRoutePage(
    connect(({ gateway, loading, menu }) => ({
        gateway,
        menu,
        loading
    }))(Gateway)
);
